﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Server;
using ESRI.ArcGIS.SystemUI;
using System.Windows.Forms;
using PlanningGIS.Win.Controls;
using ESRI.ArcGIS.Carto;
using PlanningGIS.ManageUtility.Modules;
using ESRI.ArcGIS.Geometry;
using PlanningGIS.Util.Log;
using PlanningGIS.MetaData;
using PlanningGIS.Framework.Config;
using PlanningGIS.MapSheet;
using System.IO;
using PlanningGIS.Util.Management;
using PlanningGIS.Util.Security;
using PlanningGIS.Util.Win32;
using static PlanningGIS.Util.Win32.Register;
using Microsoft.Win32;

namespace PlanningGIS.Framework
{
    /// <summary>
    /// 框架公共操作类
    /// </summary>
    public class FrameworkHelper
    {
        /// <summary>
        /// 
        /// </summary>
        public const string KEY = "PlanningGIS";

        /// <summary>
        /// 
        /// </summary>
        public const string UNLIMITED = "UNLIMITED";

        /// <summary>
        /// 
        /// </summary>
        public const string LICENSE_FILE_NAME = "license.lic";

        /// <summary>
        /// 获取或设置主窗体对象
        /// </summary>
        public static Form MdiForm { get; set; }

        /// <summary>
        /// 系统名称
        /// </summary>
        public static string SysName { get; set; }

        /// <summary>
        /// 获取或设置系统主地图
        /// </summary>
        public static IMap MainMap { get; set; }

        /// <summary>
        /// 获取主窗体的AxMapControl控件
        /// </summary>
        public static AxMapControl AxMapControl { get; set; }

        /// <summary>
        /// 当前登录的用户
        /// </summary>
        public static PlanningGIS.ManageUtility.Modules.User CurrentUser { get; set; }

        /// <summary>
        /// 应用程序框架
        /// </summary>
        public static IApplication _Application { get; set; }

        /// <summary>
        /// 属性表容器名称
        /// </summary>
        public static readonly string _DockpanelAttributeName = "属性表";


        /// <summary>
        /// 授权验证
        /// </summary>
        /// <returns></returns>
        public static bool Validate()
        {
            try
            {
                string licensePath = AppConfig.StartupPath + "\\" + LICENSE_FILE_NAME;
                if (File.Exists(licensePath) == false)
                {
                    MsgHelper.ShowWarningMsgbox("对不起，您还未对软件进行授权！");
                    return false;
                }

                string uid = OSHelper.GetComputerUID().ToUpper();

                StreamReader streamReader = streamReader = File.OpenText(licensePath.Trim());

                string license = streamReader.ReadLine();

                streamReader.Close();

                license = SecurityHelper.DeCryptDES(license, FrameworkHelper.KEY);

                string[] licenses = license.Split(';');
                if (licenses.Length != 2)
                {
                    MsgHelper.ShowWarningMsgbox("许可文件无效！");
                    return false;
                }

                string mac = licenses[0].ToUpper();
                string maturity = licenses[1].ToUpper();

                if (uid != mac)
                {
                    MsgHelper.ShowWarningMsgbox("许可文件对应的硬件序列号与本机不符！");
                    return false;
                }

                if (maturity == FrameworkHelper.UNLIMITED)
                {
                    return true;
                }
                else
                {
                    DateTime limited;
                    if (DateTime.TryParse(maturity, out limited) == false)
                    {
                        MsgHelper.ShowWarningMsgbox("许可文件无效！");
                        return false;
                    }

                    if (limited > DateTime.Now)
                    {
                        System.TimeSpan span = limited - DateTime.Now;
                        int days = span.Days;

                        if (days < 30)
                        {
                            MsgHelper.ShowInfomationMsgbox("您的许可期限还有" + days.ToString() + "天到期，如想继续使用本软件，请联系规划信息中心！");
                        }

                        return true;
                    }
                    else
                    {
                        MsgHelper.ShowWarningMsgbox("对不起，您的许可文件已过期！");
                        return false;
                    }
                }

            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("许可验证失败：" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 授权验证(临时)
        /// </summary>
        /// <param name="month">期限（月数）</param>
        /// <param name="softWareName">软件名称</param>
        /// <param name="reRegister">是否重新授权</param>
        /// <returns></returns>
        public static bool ValidateTemp(int month, string softWareName, bool reRegister = false)
        {
            try
            {
                string isPastStr = "系统已经过期";
                string key = "SOFTWARE\\zjgisSoft";
                string keyName = softWareName;
                string isPast = softWareName + "_validate";

                Register res = new Register();
                string value = res.getValue(keyType.HKEY_LOCAL_MACHINE, key, keyName);
                string pastvalue = res.getValue(keyType.HKEY_LOCAL_MACHINE, key, isPast);
                if (pastvalue != null)
                {
                    if (SecurityHelper.DeCryptDES(pastvalue, FrameworkHelper.KEY) == isPastStr) return false;
                }
                if (String.IsNullOrWhiteSpace(value) || reRegister)
                {
                    string date = SecurityHelper.EnCryptDES(DateTime.Now.AddMonths(month).ToShortDateString(), FrameworkHelper.KEY);
                    res.setValue(keyType.HKEY_LOCAL_MACHINE, key, keyName, date);
                }
                value = SecurityHelper.DeCryptDES(res.getValue(keyType.HKEY_LOCAL_MACHINE, key, keyName), FrameworkHelper.KEY);
                DateTime limited;
                try
                {
                    limited = Convert.ToDateTime(value);
                }
                catch
                {
                    throw new Exception("许可注册表出错,请先清理注册表！");
                }
                if (limited > DateTime.Now)
                {
                    System.TimeSpan span = limited - DateTime.Now;
                    int days = span.Days;
                    return true;
                }
                else
                {
                    res.setValue(keyType.HKEY_LOCAL_MACHINE, key, isPast, SecurityHelper.EnCryptDES(isPastStr, FrameworkHelper.KEY));
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }


        /// <summary>
        /// 保存编辑
        /// </summary>
        public static void SaveEdit()
        {
            IEngineEditor m_engineEditor = new EngineEditorClass();
            if (m_engineEditor.EditState == esriEngineEditState.esriEngineStateEditing)
            {
                if (m_engineEditor.HasEdits())
                {
                    DialogResult dr = MsgHelper.ShowYesOrNoQueryMsgBox("是否保存编辑？");
                    if (dr == DialogResult.Yes)
                        m_engineEditor.StopEditing(true);
                    else if (dr == DialogResult.No)
                        m_engineEditor.StopEditing(false);
                    GC.Collect();
                }
                else
                {
                    m_engineEditor.StopEditing(false);
                }
            }
        }
        
        /// <summary>
        /// 显示日志面板委托
        /// </summary>
        /// <returns></returns>
        public static InvokeEventHandler ShowLogPanelEvent = null;

        /// <summary>
        /// 显示结果面板委托
        /// </summary>
        public static InvokeEventHandler ShowRecordListEvent = null;

        /// <summary>
        /// 显示日志面板
        /// </summary>
        public static void ShowLogPanel()
        {
            ShowLogPanelEvent?.Invoke();
        }

        /// <summary>
        /// 显示结果记录面板
        /// </summary>
        public static void ShowRecordPanel()
        {
            ShowRecordListEvent?.Invoke();
        }

        /// <summary>
        /// 刷新地图委托
        /// </summary>
        public static InvokeEventHandler RefreshMapEvent = null;

        /// <summary>
        /// 刷新图层树委托
        /// </summary>
        public static InvokeEventHandler RefreshTocEvent = null;

        /// <summary>
        /// 刷新地图
        /// </summary>
        public static void RefreshMap()
        {
            RefreshMapEvent?.Invoke();
        }

        /// <summary>
        /// 刷新图层树
        /// </summary>
        public static void RefreshToc()
        {
            RefreshTocEvent?.Invoke();
        }
        /// <summary>
        /// 激活停靠面板
        /// </summary>
        /// <param name="name"></param>
        public static Control GetDockPanelControl(string name)
        {
            if (_Application == null) return null;
            return (_Application as IFramework).DockManager.GetControlFromDockPanel(name);
        }

        /// <summary>
        /// 激活停靠面板
        /// </summary>
        /// <param name="name">面板名称</param>
        /// <param name="text">面板标题</param>
        public static void ActivateDockPanel(string name,string text ="")
        {
            if (_Application == null) return;
            (_Application as IFramework).DockManager.ActivateDockPanel(name, text);
        }

        /// <summary>
        /// 增加停驻面板
        /// </summary>
        /// <param name="name">面板名称</param>
        /// <param name="control">面板中的控件</param>
        /// <param name="isReplace">是否替换同名面板</param>
        /// <param name="sides">位置</param>
        /// <param name="text"></param>
        /// <returns>是否添加成功</returns>
        public static bool AddDockPanel(string name, Control control, bool isReplace, esriDockFlags sides = esriDockFlags.esriDockRight,string text ="")
        {
            if (_Application == null) return false;
            return (_Application as IFramework).DockManager.AddDockPanel(name, control, sides, text, isReplace);
        }

        /// <summary>
        /// 初始化系统参数信息
        /// </summary>
        public static void InitParam()
        {
            try
            {
                MetaHelper.FrameConfig = ConfigHelper.GetObject<MetaConfig>();
                MetaHelper.Context = DbConnectHelper.CreateDbContextByIntance(MetaHelper.FrameConfig.ConnectName);
                SheetHelper.Config = ConfigHelper.GetObject<SheetConfig>();
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorText(ex);
            }
        }

    }
}
